package com.wjf.resourceservice.controller;

import com.wjf.common.entity.Result;
import com.wjf.resourceservice.entity.Music;
import com.wjf.resourceservice.service.MusicService;
import com.wjf.resourceservice.feign.UserClient;
import com.wjf.resourceservice.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/music")
public class MusicController {

    private static final Logger log = LoggerFactory.getLogger(MusicController.class);

    @Autowired
    private MusicService musicService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private FileService fileService;

    /**
     * 分页获取音乐列表
     */
    @GetMapping("/list")
    public Result<?> getMusicList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            List<Music> musicList = musicService.getMusicList(page, size);
            int total = musicService.getTotalCount();

            Map<String, Object> data = new HashMap<>();
            data.put("list", musicList);
            data.put("total", total);

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取音乐列表失败", e);
            return Result.error("获取音乐列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取音乐详情
     */
    @GetMapping("/{id}")
    public Result<?> getMusicDetail(@PathVariable Long id) {
        try {
            Music music = musicService.getMusicDetail(id);
            if (music == null) {
                return Result.error("音乐不存在");
            }
            return Result.success(music);
        } catch (Exception e) {
            log.error("获取音乐详情失败", e);
            return Result.error("获取音乐详情失败：" + e.getMessage());
        }
    }

    /**
     * 播放音乐
     */
    @GetMapping("/play/{id}")
    public Result<?> playMusic(@PathVariable Long id) {
        try {
            String url = musicService.playMusic(id);
            if (url == null) {
                return Result.error("音乐不存在或无法播放");
            }
            return Result.success(url);
        } catch (Exception e) {
            log.error("播放音乐失败", e);
            return Result.error("播放音乐失败：" + e.getMessage());
        }
    }

    /**
     * 下载音乐
     */
    @GetMapping("/download/{id}")
    public Result<?> downloadMusic(@PathVariable Long id) {
        try {
            String url = musicService.downloadMusic(id);
            if (url == null) {
                return Result.error("音乐不存在或无法下载");
            }
            return Result.success(url);
        } catch (Exception e) {
            log.error("下载音乐失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加音乐
     * 需要MUSIC:ADD权限
     */
    @PostMapping("/add")
    public Result<?> addMusic(@RequestBody Music music) {
        try {
            // 检查权限
            Result<Boolean> permissionResult = userClient.checkPermission("MUSIC:ADD");
            if (!Boolean.TRUE.equals(permissionResult.getData())) {
                return Result.error(403, "没有添加音乐的权限");
            }

            // 参数校验
            if (music.getTitle() == null || music.getTitle().trim().isEmpty()) {
                return Result.error("音乐标题不能为空");
            }
            if (music.getMusicUrl() == null || music.getMusicUrl().trim().isEmpty()) {
                return Result.error("音乐文件不能为空");
            }

            boolean success = musicService.addMusic(music);
            return success ? Result.success("添加成功") : Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加音乐失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新音乐信息
     * 需要MUSIC:UPDATE权限
     */
    @PutMapping("/{id}")
    public Result<?> updateMusic(@PathVariable Long id, @RequestBody Music music) {
        try {
            // 检查权限
            Result<Boolean> permissionResult = userClient.checkPermission("MUSIC:UPDATE");
            if (!Boolean.TRUE.equals(permissionResult.getData())) {
                return Result.error(403, "没有更新音乐的权限");
            }

            music.setId(id);
            boolean success = musicService.updateMusic(music);
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (Exception e) {
            log.error("更新音乐失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除音乐
     * 需要MUSIC:DELETE权限
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteMusic(@PathVariable Long id) {
        try {
            // 检查权限
            Result<Boolean> permissionResult = userClient.checkPermission("MUSIC:DELETE");
            if (!Boolean.TRUE.equals(permissionResult.getData())) {
                return Result.error(403, "没有删除音乐的权限");
            }

            boolean success = musicService.deleteMusic(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除音乐失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传音乐
     */
    @PostMapping("/upload")
    public Result<?> uploadMusic(@RequestParam("file") MultipartFile musicFile,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile,
            @RequestParam String title,
            @RequestParam String artist,
            @RequestParam String album,
            @RequestParam Integer duration,
            @RequestParam Integer vipOnly                     ) {
        try {
            // 上传音乐文件
            String musicUrl = fileService.uploadMusic(musicFile);

            // 上传封面（如果有）
            String coverUrl = null;
            if (coverFile != null) {
                coverUrl = fileService.uploadImage(coverFile);
            }

            // 创建音乐记录
            Music music = new Music();
            music.setTitle(title);
            music.setArtist(artist);
            music.setMusicUrl(musicUrl);
            music.setCoverUrl(coverUrl);
            music.setAlbum(album);
            music.setDuration(duration);
            music.setVipOnly(vipOnly);

            boolean success = musicService.addMusic(music);
            return success ? Result.success("上传成功") : Result.error("上传失败");
        } catch (Exception e) {
            log.error("上传音乐失败", e);
            return Result.error(e.getMessage());
        }
    }
}
